package com.yuan.util.file;

import com.yuan.util.string.StrUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Queue;

/**
 * 文件编码转换
 * @author YouYuan
 * @date 2020/4/27 0:01
 */
public class ConvertUnicode {

    /**
     * 批量转换文件编码
     * @param inPath 要转换的文件路径
     * @param outPath 转换完成的文件输出路径
     * @param inCode 输入文件的编码格式
     * @param outCode 输出文件的编码格式
     * @param exts 需要转换的文件的扩展名
     */
    public static void batchConvert(String inPath, String outPath, String inCode, String outCode, String... exts) throws Exception {
        String rootPath = FileUtil.coverSeparator(inPath);
        Queue<File> files = FileUtil.traversePathToQueue(rootPath);
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile() && StrUtil.strInIgnoreCase(FileUtil.getFileSuffix(fileName), exts)) {
                String inString = ReadText.readString(file, inCode);
                String absolutePath = FileUtil.coverSeparator(file.getAbsolutePath());
                int index = absolutePath.indexOf(rootPath);
                String relativePath = absolutePath.substring(index + rootPath.length());
                String outFilePath = FileUtil.coverSeparator(outPath + "/" + relativePath);
                FileUtil.createNewFile(outFilePath);
                WriteText.writeString(new File(outFilePath), inString, outCode);
                System.out.printf("读取文件:[%s], 编码:[%s] --> 保存到:[%s],编码:[%s]\n", absolutePath, inCode, outFilePath, outCode);
            }
        }
    }


    public static void main(String[] args) throws Exception {
        batchConvert("E:\\Develop\\JAVA", "E:\\Temp\\ConvertUnicode", "gbk", "utf-8", ".java");
    }

}
